package org.adorsys.aderp.jpa.xls;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.adorsys.aderp.jpa.impl.BusinessKeyInfo;
import org.adorsys.aderp.jpa.impl.RepositoryMap;
import org.adorsys.xlseasy.boot.KeyFieldInspector;
import org.adorsys.xlseasy.utils.XlseasyUtils;

public class AderpJpaKeyFieldInspector implements KeyFieldInspector {

	private Map<Class<?>, Field> businessKeyFields = new HashMap<Class<?>, Field>();

	
	public AderpJpaKeyFieldInspector(Class<?> dataClass, RepositoryMap repositoryMap) {
		List<Field> workbookFields = XlseasyUtils.readWorkbookFields(dataClass);
		for (Field field : workbookFields) {
			Class<?> elementType = XlseasyUtils.extractElementType(field);
			if(elementType==null) continue;
			
			// find business key field
			BusinessKeyInfo<?,Serializable> businessKeyInfo = repositoryMap.getBusinessKeyInfo(elementType);
			if(businessKeyInfo!=null){
				businessKeyFields.put(elementType, businessKeyInfo.getBusinessKeyField());
			}
		}
	}

	@Override
	public Field findKeyField(Class<?> sheetKlass) {
		return businessKeyFields.get(sheetKlass);
	}

}
